package org.example;

import bean.ResponseUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import bean.DB;

@WebServlet("/regOutServlet")
public class regOutServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String passagain = request.getParameter("passagain");

        // 检查密码和确认密码是否一致
        if (!password.equals(passagain)) {
            ResponseUtils.sendResponse(response, "密码和确认密码不一致", "regOut.jsp");
            return;
        }

        // 检查用户名和密码是否匹配
        DB db = new DB();
        String sql = "SELECT id FROM users WHERE username = ? AND password = ?"; // 查找用户名和密码匹配的用户

        try (Connection conn = db.createConn();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setString(1, username);  // 设置用户名
            pstmt.setString(2, password);  // 设置密码

            ResultSet rs = pstmt.executeQuery();

            if (rs.next()) {
                int userId = rs.getInt("id");  // 获取用户 ID

                // 删除用户账户
                String deleteSql = "DELETE FROM users WHERE id = ?";
                try (PreparedStatement deleteStmt = conn.prepareStatement(deleteSql)) {
                    deleteStmt.setInt(1, userId);  // 设置用户 ID
                    int rows = deleteStmt.executeUpdate();  // 执行删除

                    if (rows > 0) {
                        ResponseUtils.sendResponse(response, "账户注销成功", "login.jsp");
                    } else {
                        ResponseUtils.sendResponse(response, "删除失败，请重试", "regOut.jsp");
                    }
                }

            } else {
                ResponseUtils.sendResponse(response, "用户名或密码错误", "regOut.jsp");
            }

        } catch (SQLException e) {
            e.printStackTrace();
            ResponseUtils.sendResponse(response, "数据库操作失败", "regOut.jsp");
        } finally {
            db.close();
        }
    }
}
